package mahjong.auto.com.automahjong;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import java.nio.ByteBuffer;

/**
 * Created by heqian on 17-8-14.
 */

public class ScreenCapture {
    private static final int REQUEST_MEDIA_PROJECTION = 9001;
    private ImageReader mImageReader;
    private WindowManager mWindowManager;
    private MediaProjectionManager mMediaProjectionManager;
    private MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private Intent mIntent = null;
    private int mResultCode = 0;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ScreenCapture(Activity activity) {
        mMediaProjectionManager = (MediaProjectionManager) activity.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        activity.startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);

        mWindowManager = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public Bitmap getBitmap() {
        if (null == mMediaProjection)
            return null;

        Image image = mImageReader.acquireLatestImage();
        if(null == image)
            return null;

        int width = image.getWidth();
        int height = image.getHeight();
        final Image.Plane[] planes = image.getPlanes();

        final ByteBuffer buffer = planes[0].getBuffer();
        int pixelStride = planes[0].getPixelStride();
        int rowStride = planes[0].getRowStride();
        int rowPadding = rowStride / pixelStride - width;

        Bitmap bitmap = Bitmap.createBitmap(width + rowPadding, height, Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buffer);
        image.close();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void startVirtual() {
        if (null != mMediaProjection) {
            virtualDisplay();

        } else {
            getMediaProjection();

            if (null != mMediaProjection)
                virtualDisplay();
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void getMediaProjection() {
        if (null != mIntent)
            mMediaProjection = mMediaProjectionManager.getMediaProjection(mResultCode, mIntent);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void virtualDisplay() {
        Point size = new Point();
        if (null != mImageReader) {
            mImageReader.close();
        }

        DisplayMetrics metrics = new DisplayMetrics();
        mWindowManager.getDefaultDisplay().getMetrics(metrics);
        mWindowManager.getDefaultDisplay().getSize(size);
        mImageReader = ImageReader.newInstance(size.x, size.y, 0x1, 2); //ImageFormat.RGB_565``

        mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror",
                size.x, size.y, metrics.densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mImageReader.getSurface(), null, null);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void stopMediaProjection() {
        if (mMediaProjection != null) {
            mMediaProjection.stop();
            mMediaProjection = null;
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void stopVirtual() {
        if (null != mImageReader) {
            mImageReader.close();
            mImageReader = null;
        }

        if (null != mVirtualDisplay) {
            mVirtualDisplay.release();
            mVirtualDisplay = null;
        }
    }


    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == REQUEST_MEDIA_PROJECTION) {
            if (resultCode == MainActivity.RESULT_OK && intent != null && resultCode != 0) {
                mIntent = intent;
                mResultCode = resultCode;
            }
        }
    }


}
